#!/bin/bash

function check_samba {
    if dpkg -s samba >/dev/null 2>&1; then
        echo "Samba已安装"
        return 0
    else
        echo "Samba未安装"
        return 1
    fi
}

function install_samba {
    echo "正在安装Samba..."
    sudo apt-get install samba
    post_install_menu
}

function create_share {
    read -p "请输入共享目录的路径: " dir_path
    read -p "请输入共享目录的名称: " share_name
    read -p "请输入权限（只读：ro，可写：rw）: " permission
    read -p "是否允许匿名访问（是：yes，否：no）: " anonymous
    read -p "请输入允许访问的用户名（所有用户：all，特定用户请输入用户名）: " user
    if [ "$user" != "all" ]; then
        if id -u "$user" >/dev/null 2>&1; then
            echo "用户已存在"
        else
            echo "用户不存在，正在创建..."
            sudo useradd $user
        fi
        echo -ne "\n" | sudo smbpasswd -a $user
    fi
    echo "[$share_name]" | sudo tee -a /etc/samba/smb.conf
    echo "path = $dir_path" | sudo tee -a /etc/samba/smb.conf
    echo "browseable = yes" | sudo tee -a /etc/samba/smb.conf
    if [ "$permission" = "ro" ]; then
        echo "read only = yes" | sudo tee -a /etc/samba/smb.conf
    else
        echo "read only = no" | sudo tee -a /etc/samba/smb.conf
    fi
    if [ "$anonymous" = "yes" ]; then
        echo "guest ok = yes" | sudo tee -a /etc/samba/smb.conf
    else
        echo "guest ok = no" | sudo tee -a /etc/samba/smb.conf
    fi
    if [ "$user" != "all" ]; then
        echo "valid users = $user" | sudo tee -a /etc/samba/smb.conf
    fi
    echo "创建共享目录成功"
}

function list_shares {
    testparm -s /etc/samba/smb.conf | grep -E "^\["
}

function modify_share {
    read -p "请输入要修改的共享名称: " share_name
    sudo sed -i "/\[$share_name\]/,/^\[/d" /etc/samba/smb.conf
    create_share
}

function pre_install_menu {
    while true
    do
        echo "1. 安装Samba"
        echo "2. 退出"
        read -p "请选择一个操作: " opt
        case $opt in
            1)
                install_samba
                ;;
            2)
                break
                ;;
            *)
                echo "无效的选项"
                ;;
        esac
    done
}

function post_install_menu {
    while true
    do
        echo "1. 创建共享目录"
        echo "2. 浏览现有共享列表"
        echo "3. 修改已有共享"
        echo "4. 退出"
        read -p "请选择一个操作: " opt
        case $opt in
            1)
                create_share
                ;;
            2)
                list_shares
                ;;
            3)
                modify_share
                ;;
            4)
                break
                ;;
            *)
                echo "无效的选项"
                ;;
        esac
    done
}

if check_samba; then
    post_install_menu
else
    pre_install_menu
fi
